﻿#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define SERVER_IP "127.0.0.1"
#define SERVER_PORT 9999
#define BUF_SIZE 1024
using std::cin;
using std::cout;
using std::endl;
using std::string;
void Error(const string &msg)
{
  cout << msg << " error!" << endl;
  exit(-1);
}
void Print(const string &msg)
{
  cout << msg << endl;
}
int main()
{
  // step01:创建客户端套接字
  int sock_clnt;
  if ((sock_clnt = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
    Error("socket()");
  Print("socket() ok ...");
  // step02:连接服务端监听套接字
  sockaddr_in addr_serv{};
  addr_serv.sin_family = AF_INET;
  addr_serv.sin_addr.s_addr = inet_addr(SERVER_IP);
  addr_serv.sin_port = htons(SERVER_PORT);
  if (connect(sock_clnt, (sockaddr *)&addr_serv, sizeof(addr_serv)) == -1)
    Error("connect()");
  Print("connect() ok ...");
  // step03:开始传输数据
  string msg;
  cout << "Please input message: ";
  std::getline(cin, msg);
  cout << msg << endl;
  send(sock_clnt, msg.c_str(), sizeof(msg), 0);
  shutdown(sock_clnt, SHUT_WR);
  char response[BUF_SIZE];
  recv(sock_clnt, response, sizeof(response), 0);
  cout << "Received response: " << response << endl;
  close(sock_clnt);
  return 0;
}